// app.js
const express = require('express');
const cors = require('cors');
const mysql = require('mysql2/promise');
const dotenv = require('dotenv');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

// 加载环境变量
dotenv.config();

// 创建 Express 应用
const app = express();
const PORT = process.env.PORT || 3000;

// 配置数据库连接池
const pool = mysql.createPool({
    host: process.env.MYSQL_HOST || 'localhost',
    user: process.env.MYSQL_USER || 'root',
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE || 'gameDB',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// 中间件
app.use(cors());
app.use(express.json());

// 验证 JWT 令牌的中间件
const authenticateToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) return res.status(401).json({ message: '认证令牌缺失' });

    jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key', (err, user) => {
        if (err) return res.status(403).json({ message: '无效令牌' });
        req.user = user;
        next();
    });
};

// 用户路由
app.post('/users/register', async (req, res) => {
    try {
        const { username, password } = req.body;

        // 检查用户是否已存在
        const [users] = await pool.execute('SELECT * FROM users WHERE username = ?', [username]);
        if (users.length > 0) {
            return res.status(400).json({ message: '用户名已存在' });
        }

        // 加密密码
        const hashedPassword = await bcrypt.hash(password, 10);

        // 创建新用户
        const [result] = await pool.execute(
            'INSERT INTO users (username, password) VALUES (?, ?)',
            [username, hashedPassword]
        );

        res.status(201).json({ message: '用户注册成功', userId: result.insertId });
    } catch (error) {
        res.status(500).json({ message: '服务器错误', error: error.message });
    }
});

app.post('/users/login', async (req, res) => {
    try {
        const { username, password } = req.body;

        // 获取用户
        const [users] = await pool.execute('SELECT * FROM users WHERE username = ?', [username]);
        const user = users[0];

        if (!user) {
            return res.status(401).json({ message: '认证失败' });
        }

        // 验证密码
        const isPasswordValid = await bcrypt.compare(password, user.password);
        if (!isPasswordValid) {
            return res.status(401).json({ message: '认证失败' });
        }

        // 生成 JWT 令牌
        const token = jwt.sign(
            { userId: user.id, username: user.username },
            process.env.JWT_SECRET || 'your-secret-key',
            { expiresIn: '1h' }
        );

        res.json({ token });
    } catch (error) {
        res.status(500).json({ message: '服务器错误', error: error.message });
    }
});

// 游戏路由
app.get('/games', authenticateToken, async (req, res) => {
    try {
        const [games] = await pool.execute('SELECT * FROM games');
        res.json(games);
    } catch (error) {
        res.status(500).json({ message: '服务器错误', error: error.message });
    }
});

app.get('/games/:id', authenticateToken, async (req, res) => {
    try {
        const [games] = await pool.execute('SELECT * FROM games WHERE id = ?', [req.params.id]);
        if (games.length === 0) {
            return res.status(404).json({ message: '游戏不存在' });
        }
        res.json(games[0]);
    } catch (error) {
        res.status(500).json({ message: '服务器错误', error: error.message });
    }
});

// 收藏路由
app.post('/users/me/favorites', authenticateToken, async (req, res) => {
    try {
        const { gameId } = req.body;
        const userId = req.user.userId;

        // 检查是否已收藏
        const [favorites] = await pool.execute(
            'SELECT * FROM favorites WHERE user_id = ? AND game_id = ?',
            [userId, gameId]
        );

        if (favorites.length > 0) {
            return res.status(400).json({ message: '游戏已收藏' });
        }

        // 添加收藏
        await pool.execute(
            'INSERT INTO favorites (user_id, game_id) VALUES (?, ?)',
            [userId, gameId]
        );

        res.status(201).json({ message: '收藏成功' });
    } catch (error) {
        res.status(500).json({ message: '服务器错误', error: error.message });
    }
});

app.get('/users/me/favorites', authenticateToken, async (req, res) => {
    try {
        const userId = req.user.userId;

        // 获取用户收藏的游戏
        const [favorites] = await pool.execute(`
      SELECT games.* 
      FROM favorites 
      JOIN games ON favorites.game_id = games.id 
      WHERE favorites.user_id = ?
    `, [userId]);

        res.json(favorites);
    } catch (error) {
        res.status(500).json({ message: '服务器错误', error: error.message });
    }
});

// 启动服务器
async function startServer() {
    try {
        // 测试数据库连接
        const connection = await pool.getConnection();
        console.log('MySQL 连接成功');
        connection.release();

        // 启动服务器
        app.listen(PORT, () => {
            console.log(`服务器运行在端口 ${PORT}`);
        });
    } catch (err) {
        console.error('无法连接到数据库:', err);
        process.exit(1); // 连接失败时终止进程
    }
}

startServer();